﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace WebTraderLiteCL
{
    public class stockDataQuery
    {
        public float getCurrentPrice(string symbol)
        {
            float price = -999;
            //string format = "e1snl1"; // e1 = error indicator, s = symbol, n = company name, l1 = last trade price
            string format = "e1l1";
            Stream srcStream = queryStockDataSource(symbol, format);

            StreamReader read = new StreamReader(srcStream);
            
            //read the csv content
            string content = read.ReadToEnd();
                string[] dataElem = content.Split(',');
                if (!string.Equals(dataElem[0], "\"N/A\""))
                {
                    Console.Write("Unknown symbol!\n");
                }
                else
                {                   
                    price = float.Parse(dataElem[1]);
                }
            return price;
        }
        public int getShareOutStanding(String symbol)
        {
            Int32 shareOwned = -999;
            //string format = "e1snl1"; // e1 = error indicator, s = symbol, n = company name, l1 = last trade price
            string format = "e1v";
            Stream srcStream = queryStockDataSource(symbol, format);

            StreamReader read = new StreamReader(srcStream);

            //read the csv content
            string content = read.ReadToEnd();
            string[] dataElem = content.Split(',');
            if (!string.Equals(dataElem[0], "\"N/A\""))
            {
                Console.Write("Unknown symbol!\n");
            }
            else
            {
                shareOwned =Int32.Parse(dataElem[1]);
            }
            return shareOwned;
        }
        public string getCompanyName(string symbol)
        {
            string name = "NULL";
            //string format = "e1snl1"; // e1 = error indicator, s = symbol, n = company name, l1 = last trade price
            string format = "e1n";
            Stream srcStream = queryStockDataSource(symbol, format);

            StreamReader read = new StreamReader(srcStream);

            //read the csv content
            string content = read.ReadToEnd();
            string[] dataElem = content.Split(',');
            if (!string.Equals(dataElem[0], "\"N/A\""))
            {
                Console.Write("Unknown symbol!\n");
            }
            else
            {
                name = dataElem[1].Trim().TrimStart('"').TrimEnd('\n', '"'); //set name, and trim newline character if there
            }
            return name;
        }


        //Adapted from http://www.jarloo.com/get-historical-stock-data/
        //the source will exclude days that were weekends (since stock markets are closed), so if your to or from day happened to be a weekend, it will pick the closest
        //date that the market was open before that day
        public List<HistoricalStockData> getHistoricalData(string symbol, DateTime fromDate, DateTime toDate)
        {
            //http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2004&g=d&a=3&b=12&c=1998&ignore=.csv
            //sn = TICKER
            //a = fromMonth-1
            //b = fromDay (two digits)
            //c = fromYear
            //d = toMonth-1
            //e = toDay (two digits)
            //f = toYear
            //g = d for day, m for month, y for yearly       

            string url = "http://ichart.finance.yahoo.com/table.csv?s=||SYM||&d=||TOMONTH||&e=||TODAY||&f=||TOYEAR||&g=d&a=||FROMMONTH||&b=||FROMDAY||&c=||FROMYEAR||&ignore=.csv";
            url = url.Replace("||SYM||", symbol);
            url = url.Replace("||TOMONTH||", (toDate.Month - 1).ToString() );
            url = url.Replace("||TOYEAR||", toDate.Year.ToString());
            url = url.Replace("||TODAY||", toDate.Day.ToString("D2"));
            url = url.Replace("||FROMMONTH||", (fromDate.Month - 1).ToString());
            url = url.Replace("||FROMYEAR||", fromDate.Year.ToString());
            url = url.Replace("||FROMDAY||", fromDate.Day.ToString("D2"));

            //Make http request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                WebResponse resp = req.GetResponse();
                //Get the response
                Stream srcStream = resp.GetResponseStream();
                StreamReader read = new StreamReader(srcStream);

                //read the csv content
                string content = read.ReadToEnd();
                //Console.Write(content);

                string[] rows = content.Split('\n');
                List<HistoricalStockData> history = new List<HistoricalStockData>();

                for (int i = 1; i < rows.Length; i++)
                {
                    if (rows[i].Equals("")) continue;
                    string[] cols = rows[i].Split(','); //Date, Open, High, Low, Close, Volume, Adj Close
                    HistoricalStockData data = new HistoricalStockData();
                    data.Date = Convert.ToDateTime(cols[0]);
                    data.Open = Convert.ToDouble(cols[1]);
                    data.High = Convert.ToDouble(cols[2]);
                    data.Low = Convert.ToDouble(cols[3]);
                    data.Close = Convert.ToDouble(cols[4]);
                    data.Volume = Convert.ToDouble(cols[5]);
                    data.AdjClose = Convert.ToDouble(cols[6]);
                    history.Add(data);
                }



                return (history);
            }
            catch (WebException ex)
            {

                return null;
            }

            

     }




        //Query CSV source directly, returns a stream to be parsed by the calling method
        private Stream queryStockDataSource(string symbol, string formatSTR)
        {
            string url = "http://finance.yahoo.com/d/quotes.csv?s=||SYM||&f=||FORMAT||";
            url = url.Replace("||SYM||", symbol);
            url = url.Replace("||FORMAT||", formatSTR);
            

            //Make http request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            WebResponse resp = req.GetResponse();

            //Get the response
            Stream receive = resp.GetResponseStream();
            //StreamReader read = new StreamReader(receive);

            //read the csv content
            //string content = read.ReadToEnd();
            
            //Console.Write(content);

            return (receive);


        }

        public Stock getStockInfo(string symbol)
        {
            //string format = "e1snl1"; // e1 = error indicator, s = symbol, n = company name, l1 = last trade price
            string format = "e1n";
            Stream srcStream = queryStockDataSource(symbol, format);

            StreamReader read = new StreamReader(srcStream);

            Stock stk = null;
            //read the csv content
            string content = read.ReadToEnd();
            string[] dataElem = content.Split(',');
            if (!string.Equals(dataElem[0], "\"N/A\""))
            {
                Console.Write("Unknown symbol!\n");
            }
            else
            {
                stk = new Stock(symbol);                
            }
            return stk;
        }
        



    }
}
